<template>
  <section>
    <div class="button-group">
      <el-button type="primary" @click="addGateway">新增</el-button>
      <!-- <el-button type="warning" >导出</el-button> -->
    </div>
    <ft-table
      ref="gatewayTable"
      :data="gatewayData"
      :columns="gatwayColumns"
      :expand-row-keys="['name']"
      row-key="name"
      @expand-change="gatewayExpand"
      :cell-style="{background: 'rgba(84, 92, 100, 0.25)'}"
    >
            

      <template #expand="{ row }">
        <!-- 通道 -->
        <ft-table
          ref="chanelTable"
          :data="chanelData"
          :columns="chanelColumns"
          :expand-row-keys="['com']"
          row-key="com"
          @expand-change="chanelExpand"
          :cell-style="{background: 'rgba(84, 92, 100, 0.33)'}"
        >
         
          <template #expand="{ row }">
            <!-- 设备 -->
            <ft-table
              ref="deviceTable"
              :data="deviceData"
              :columns="deviceColumns"
              :expand-row-keys="['name']"
              row-key="name"
              @expand-change="deviceExpand" 
              :cell-style="{background: 'rgba(84, 92, 100, 0.4)'}"
            >

              <template #expand="{ row }">
                <!-- tag -->
                <ft-table
                  ref="tagTable"
                  :data="tagData"
                  :columns="tagColumns"
                  :expand-row-keys="['name']"
                  row-key="name"
                  :cell-style="{background: 'rgba(84, 92, 100, 0.5)'}"
                >
                  <template #operation="{ row }">
                    <i
                      class="el-icon-edit-outline color-blue left-space"
                      @click="editTag(row)"
                    ></i>
                    <i class="el-icon-delete color-danger left-space" @click="delTag(row)"></i>
                  </template>
                </ft-table>
              </template>


              <template #operation="{ row }">
                <el-button type="text" @click="addTag(row)">添加TAG</el-button>
                <el-button type="text" @click="importTag(row)">
                  <el-upload ref="upload" 
                    :action="action"
                    :show-file-list="false"
                    :on-success="tagUploadSuccess"
                    :on-error="tagUploadError"
                    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
                    导入TAG
                  </el-upload>
                </el-button>
                <i
                  class="el-icon-edit-outline color-blue left-space"
                  @click="editDevice(row)"
                ></i>
                <i class="el-icon-delete color-danger left-space" @click="delDevice(row)"></i>
              </template>
            </ft-table>
          </template>   



          <template #operation="{ row }">
            <el-button type="text" @click="addDevice(row)">添加设备</el-button>
            <i
              class="el-icon-edit-outline color-blue left-space"
              @click="editChanel(row)"
            ></i>
            <i class="el-icon-delete color-danger left-space" @click="delChanel(row)"></i>
          </template>
        </ft-table>
      </template>


      <template #operation="{ row }">
        <el-button type="text" :loading="restartGatewayLoading" @click="restartGateway(row)">重启</el-button>
        <el-button type="text" :loading="resetGatewayLoading" @click="resetGateway(row)">恢复出场设置</el-button>
        <el-button type="text" @click="bindUser(row)">分配用户</el-button>
        <el-button type="text" @click="exportGwConf(row)">导出</el-button>
        <el-button type="text" @click="updateIp(row)">IP设置</el-button>
        <el-button type="text" @click="addChanel(row)">添加通道</el-button>
      
        <el-button type="text" icon="el-icon-edit-outline"  @click="editGateway(row)"></el-button>
        <i class="el-icon-delete color-danger left-space" @click="delGateway(row)"></i>
      </template>
    </ft-table>
    

    <el-drawer
      ref="drawer"
      :visible.sync="showDrawer"
      :with-header="false"
    >
      <h3>{{drawerTitle}}</h3>
      <div class="form-body">
        <form-gateway v-if="/网关/.test(drawerTitle)" :data="gateway" @close="showDrawer=false" @refresh="refreshGateway"></form-gateway>
        <form-chanel v-if="/通道/.test(drawerTitle)" :data="chanel" @close="showDrawer=false" @refresh="refreshChanel"></form-chanel>
        <form-device v-if="/设备/.test(drawerTitle)" :data="device" @close="showDrawer=false" @refresh="refreshDevice"></form-device>
        <form-tag v-if="/TAG/.test(drawerTitle)" :data="tag" @close="showDrawer=false" @refresh="refreshTag"></form-tag>
        <form-ip v-if="/IP/.test(drawerTitle)" ref="ip" :data="ip" @close="showDrawer=false" ></form-ip>
      </div>

    </el-drawer>
  
    <el-dialog
      title="请选择用户后导出网关配置"
      :visible.sync="gatewayDialog"
      width="30%"
     >
      
      <el-form :model="user" :rules="userRules" ref="user"> 
        <el-form-item label="用户名称" prop="id">
          <el-select v-model="user.id" placeholder="请选择用户名称">
            <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.user"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="gatewayDialog = false">取 消</el-button>
        <el-button type="primary" :loading="dialogLoading" @click="confirmExport">确 定</el-button>
      </span>
    </el-dialog>  

    <el-dialog
      :visible.sync="showBindUser"
      width="100%"
    >
      <the-user :data="gateway" @close="showBindUser=false"></the-user>
    </el-dialog>

  </section>
</template>

<script>
import {
  gatewayApi,
  deviceApi,
  chanelApi,
  tagApi,
  exportGwConfApi,
  delGatewayApi,
  delChanelApi,
  delDeviceApi,
  delTagApi,
  restartGatewayApi,
  resetGatewayApi
} from '@/api/setting.js'

import {
  isDel, 
  isConfirm
} from '@/util/comman'

import {
  getUserApi
} from '@/api/user'
import config from '@/../config'
import {mapGetters} from 'vuex';

import FormGateway from './form-gateway'
import FormChanel from './form-chanel'
import FormDevice from './form-device'
import FormTag from './form-tag'
import FormIp from './form-ip'
import TheUser from '../user'

export default {
  name: 'device',
  components: {
    FormGateway,
    FormChanel,
    FormDevice,
    FormTag,
    FormIp,
    TheUser
  },
  data(){
    return {
      gatwayColumns:[
        { prop: "expand",align: "center", type: 'expand', slot: true },
        { prop: "name", label: "网关名称", align: "center" },
        { prop: "sn", label: "SN码", align: "center" },
        { prop: "ip", label: "ip", align: "center" },
        { prop: "company", label: "公司名称", align: "center" },
        { prop: "phone", label: "联系电话", align: "center" },
        { prop: "addr", label: "联系地址", align: "center" },
        { prop: "operation", label: "操作", align: "center", slot: true },
      ],
      gatewayData: [],
      chanelColumns:[
        { prop: "expand",align: "center", type: 'expand', slot: true },
        { prop: "type", label: "类型", align: "center" },
        { prop: "protocol", label: "协议", align: "center" },
        { prop: "com", label: "端口", align: "center" },
        { prop: "bps", label: "波特率", align: "center" },
        { prop: "data_bit", label: "数据位", align: "center" },
        { prop: "stop_bit", label: "停止位", align: "center" },
        { prop: "check_bit", label: "校验位", align: "center" },
        { prop: "cycle", label: "超时周期(ms)", align: "center" },
        { prop: "operation", label: "操作", align: "center", slot: true },
      ],
      chanelData: [],
      deviceColumns:[
        { prop: "expand",align: "center", type: 'expand', slot: true },
        { prop: "name", label: "设备名称", align: "center" },
        { prop: "address", label: "设备地址", align: "center" },
        { prop: "two_byte_int", label: "2字节整数", align: "center" },
        { prop: "four_byte_int", label: "4字节整数", align: "center" },
        { prop: "four_byte_float", label: "4字节浮点数", align: "center" },
        { prop: "eight_byte_float", label: "8字节浮点数", align: "center" },
        { prop: "endian", label: "字符串", align: "center" },
        { prop: "operation", label: "操作", align: "center", slot: true },
      ],
      deviceData: [],
      tagColumns:[
        { prop: "name", label: "TAG名称", align: "center" },
        { prop: "func_code", label: "功能码", align: "center" },
        { prop: "register_start_address", label: "寄存器起始地址", align: "center" },
        { prop: "data_type", label: "数据类型", align: "center" },
        { prop: "register_num", label: "寄存器个数", align: "center" },
        { prop: "rate", label: "倍率", align: "center" },
        { prop: "control_type", label: "读写标识", align: "center" },
        { prop: "operation", label: "操作", align: "center", slot: true },
      ],
      tagData: [],
      drawerTitle: '网关',
      showDrawer: false,
      loading: false,
      gateway:{},
      chanel:{},
      device:{},
      tag: {},
      action: '',
      gatewayDialog: false,
      user:{
        id: ''
      },
      users: [],
      userRules:{
        id: [{required: true, trigger: 'blur', message: '请选择用户名称'}]
      },
      dialogLoading: false,
      currentGw: {},
      ip: {},
      restartGatewayLoading: false,
      resetGatewayLoading: false,
      showBindUser: false,
    }
  },
  computed: {
    ...mapGetters(['SYS_PARAMS'])
  },
  mounted(){
    this.refreshGateway();
    this.getUsers();
  },
  methods: {
    getUsers(){
      getUserApi().then(res =>{
        if(res.code == 0) this.users = res.data;
      })
    },
    refreshGateway(data){
      gatewayApi(data).then(res=>{
        if(res.code == 0){
          this.gatewayData = res.data;
        }
      })
    },
    refreshDevice(data){
       deviceApi(data).then(res=>{
        if(res.code == 0){
          this.deviceData = res.data;
        }
      })
    },
    refreshChanel(data){
       chanelApi(data).then(res=>{
        if(res.code == 0){
          this.chanelData = res.data;
        }
      })
    },
    refreshTag(data){
       tagApi(data).then(res=>{
        if(res.code == 0){
          this.tagData = res.data;
        }
      })
    },
    addGateway(){
      this.drawerTitle = '新增网关'
      this.showDrawer = true;
      this.gateway = {
        transfer_type: '网口',
        transfer_protocol: 'mqtt',
        QOS: 'QOS0'
      };
    },
    addChanel(row){
      this.chanel = {
        parent_id: row.id,
        type: '网口',
        protocol: 'modbus',
        com: 'com1',
        bps: '9600',
        data_bit: '8',
        stop_bit: '1',
        check_bit: 'N',
        cycle: '500',
      }
      this.drawerTitle = '新增通道'
      this.showDrawer = true;
    },
    addDevice(row){
      this.device = {
        'parent_id': row.id,
        'chanel_no': row.com,
        'name': '',
        'address': '',
        'two_byte_int': 'AB',
        'four_byte_int': 'AB CD',
        'four_byte_float': 'AB CD',
        'eight_byte_float': 'AB CD EF GH',
        'endian': 'Little',
      };
      this.drawerTitle = '新增设备'
      this.showDrawer = true
      this.$refs.chanelTable.toggleRowExpansion(row)
    },

    addTag(row){
      this.tag = {
        parent_id: row.id,
        chanel_no: row.com,
        device_addr: row.addr,
        chanel_id: row.parent_id,
        name: '',
        func_code: '01',
        register_start_address: '',
        register_num: '',
        rate: '9600',
        control_type: 'RO',
      };
      this.drawerTitle = '新增TAG'
      this.showDrawer = true
      this.$refs.deviceTable.toggleRowExpansion(row)
    },
    updateIp(row){
      this.ip = row;
      this.drawerTitle = '更改IP配置'
      this.showDrawer = true;
      this.$nextTick(()=>{
        this.$refs.ip.getIpConfig();
      })
    },
    gatewayExpand(row){
      this.refreshChanel({parent_id: row.id});
    },
    chanelExpand(row){
      this.refreshDevice({parent_id: row.id});

    },
    deviceExpand(row){
      this.refreshTag({parent_id: row.id});
    },
    editGateway(row){
      this.drawerTitle = '编辑网关';
      this.showDrawer = true;
      this.gateway = row;
    },
    editChanel(row){
      this.drawerTitle = '编辑通道';
      this.showDrawer = true;
      this.device = row;
    },
    editDevice(row){
      this.drawerTitle = '编辑设备';
      this.showDrawer = true;
      this.chanel = row;
    },
    editTag(row){
      this.drawerTitle = '编辑TAG';
      this.showDrawer = true;
      this.tag = row;
    },
    async delGateway(row){
      const flag = await isDel(row.name);
      if(!flag) return;
      delGatewayApi({id: row.id}).then(res => {
        if(res.code == 0){
          this.$message({type: 'success', message: '网关删除成功'})
          this.refreshGateway();
        }else{
          this.$message({type: 'warning', message: '网关删除失败'})
        }
      })
    },
    async delChanel(row){
      const flag = await isDel(row.com);
      if(!flag) return;
      delChanelApi({id: row.id}).then(res => {
        if(res.code == 0){
          this.$message({type: 'success', message: '通道删除成功'})
          this.refreshChanel({parent_id: row.parent_id});
        }else{
          this.$message({type: 'warning', message: '通道删除失败'})
        }
      })
    },
    async delDevice(row){
      const flag = await isDel(row.name);
      if(!flag) return;
      delDeviceApi({id: row.id}).then(res => {
        if(res.code == 0){
          this.$message({type: 'success', message: '设备删除成功'})
          this.refreshDevice({parent_id: row.parent_id});
        }else{
          this.$message({type: 'warning', message: '设备删除失败'})
        }
      })
    },
    async delTag(row){
      const flag = await isDel(row.name);
      if(!flag) return;
      delTagApi({id: row.id}).then(res => {
        if(res.code == 0){
          this.$message({type: 'success', message: 'tag删除成功'})
          this.refreshTag({parent_id: row.parent_id});
        }else{
          this.$message({type: 'warning', message: 'tag删除失败'})
        }
      })
    },
    exportGwConf(row){
      this.gatewayDialog = true;
      this.currentGw = row;
      this.user.id = '';
    },
    confirmExport(){
      this.$refs.user.validate(valid => {
        if(valid) {

          this.dialogLoading = true;
          const data = {
            ...this.currentGw,
            userName: this.user.name,
          }
          exportGwConfApi(data).then(res=>{
            this.dialogLoading = false;
            this.gatewayDialog = false;
            if(res.code == 0 ){


            }
          })

        }
      });
     
    },
    importTag(row){
      this.action = config.baseURL + ':' + config.http_server_port + '/tag/addByFile?parent=' + row.parent_id;
    },
    tagUploadSuccess(res){
      if(res.code == 0)  this.$message({ type: 'success', message: '文件上传成功' })
      else this.$message({ type: 'warning', message: '文件上传失败' })
    },
    tagUploadError(){
       this.$message({ type: 'warning', message: '文件上传失败' })
    },
    async restartGateway(row){
      const flag = await isConfirm(`即将重启网关：${row.name},是否继续?`)
      if(!flag) return;
      this.restartGatewayLoading = true;
      restartGatewayApi()
      .then(res=>{
        this.restartGatewayLoading = false;

        if(res.code == 0){
          this.$message({type: 'success', message: '重启成功'})
        }
      })
    },
    async resetGateway(row){
      const flag = await isConfirm(`网关${row.name}即将恢复出厂设置,是否继续?`)
      if(!flag) return;
      this.resetGatewayLoading = true;

       resetGatewayApi()
      .then(res=>{
        this.resetGatewayLoading = false;
         if(res.code == 0){
           this.$message({type: 'success', message: '恢复出厂设置成功'})
         }
      })
    },
    bindUser(row){
      this.gateway = row;
      this.showBindUser = true;
    }
  }
}
</script>
<style lang="scss" scoped>
.button-group{
 display: flex;
 justify-content: flex-end;
 padding: 10px;
}
.form-body{
  max-height: 75vh;
  overflow: auto;
}


</style>